// 用户列表
import React, { useState, useEffect } from "react";
import ContentTitle from "@/components/contentTitle/ContentTitle";
import style from './list.module.less'
import { Table, Button, Pagination, message, Modal, Form, Input, Select } from 'antd';
import { getUserList, deleteUser, editUser ,batchDelete} from '@/api/users'
import moment from "moment";

const AccountList = () => {
    // 定义表格数据行
    const columns = [
        {
            title: '账号',
            dataIndex: 'account',
        },
        {
            title: '用户组',
            dataIndex: 'userGroup',
        },
        {
            title: '创建时间',
            dataIndex: 'ctime',
        },
        {
            title: '操作',
            render: (_, record) => (
                <>
                    <Button type="primary" className={style.mr} onClick={() => showDeleModal(record)}>编辑</Button>
                    <Button type="primary" danger className={style.mr} onClick={() => { showModal(record.id) }}>删除</Button>
                </>
            )
        },
    ];
    const [dataSource, setDataSource] = useState([
        {
            key: '1',
            id: null,
            ctime: 'xx',
            account: 'xx',
            userGroup: '',
            imgUrl: ''
        }
    ]);
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [showEditModal, setShowEditModal] = useState(false);
    const [editData, setEditData] = useState({
        id: null,
        account: '',
        userGroup: '',
    });
    const [form] = Form.useForm();
    const [rows,setRows]= useState();


    const getList = async (currentPage, pageSize) => {
        try {
            const { data, total } = await getUserList(currentPage, pageSize);
            // 确保每个数据项都有唯一的 key
            const newDataSource = data.map(item => ({ ...item, key: item.id,ctime: moment(item.ctime).format('YYYY-MM-DD HH:mm:ss') }));
            setDataSource(newDataSource);
            setTotal(total);
        } catch (error) {
            message.error('获取用户列表失败，请稍后重试');
        }
    };

    useEffect(() => {
        getList(currentPage, pageSize);
    }, [currentPage, pageSize]);

    const change = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    const handleDelete = async (id) => {
        try {
            const { code, msg } = await deleteUser({ id });
            if (code === 0) {
                message.success(msg);
                getList(currentPage, pageSize);
            } else {
                message.error(msg);
            }
        } catch (error) {
            message.error('删除用户失败，请稍后重试');
        }
    };

    const handleCancel = (text) => {
        message.error(text);
        setShowEditModal(false);
        form.resetFields();
    };

    const showModal = (id) => {
        Modal.confirm({
            title: '删除用户提示',
            content: '确定要删除该用户吗',
            okText: '确定',
            cancelText: '取消',
            onOk: () => handleDelete(id),
            onCancel: () => handleCancel('取消删除')
        });
    };

    const handleEdit = async () => {
        try {
            await form.validateFields();
            const values = await form.getFieldsValue();
            const updatedData = { ...editData, ...values };
            const { code, msg } = await editUser(updatedData);
            if (code === 0) {
                message.success(msg);
                setShowEditModal(false);
                getList(currentPage, pageSize);
                form.resetFields();
            } else {
                message.error(msg);
            }
        } catch (errorInfo) {
            message.error('表单验证失败，请检查输入');
        }
    };

    const showDeleModal = (row) => {
        setShowEditModal(true);
        const { id, account, userGroup } = row;
        setEditData({ id, account, userGroup });
        form.setFieldsValue({ account, userGroup });
    };
    const onSelect = (record, selected, selectedRows, nativeEvent) => {
        setRows(selectedRows);
        //selectedRows:选中行
        //record:当前行
        //selected:当前行是否选中
        //nativeEvent:原生事件对象
    }
    const deleUsers = async () => {
        if(rows){
            const ids = rows.map(item => item.id);
            try {
                const { code, msg } = await batchDelete({ids:JSON.stringify(ids)});
                if (code === 0) {
                    message.success(msg);
                    getList(currentPage, pageSize);
                } else {
                    message.error(msg);
                }
            } catch (errorInfo) {
                message.error('表单验证失败，请检查输入');
            }
        }else{
            message.error('请选择要删除的数据');
        }
    }

    return (
        <>
            <ContentTitle title="账号管理">
                <Button onClick={deleUsers}>批量删除</Button>
            </ContentTitle>

            <div>
                <Table
                    rowSelection={{ type: 'checkbox', onSelect }}
                    // rowSelection={onSelect}
                    columns={columns}
                    dataSource={dataSource}
                    pagination={false}
                    onRow={(record) => {
                        return {
                            record: record.id
                        };
                    }}
                />
                <Pagination
                    key={`${currentPage}-${pageSize}`}
                    total={total}
                    showSizeChanger
                    showQuickJumper
                    defaultCurrent={currentPage}
                    defaultPageSize={pageSize}
                    showTotal={total => `共 ${total} 条`}
                    onChange={change}
                    pageSizeOptions={['5', '10', '15', '20']}
                    style={{ marginTop: 20 }}
                />
            </div>

            {/* 修改框 */}
            <Modal
                open={showEditModal}
                title="修改用户信息"
                onCancel={() => handleCancel('取消修改')}
                onOk={() => handleEdit()}
            >
                <Form
                    name="basic"
                    form={form}
                    initialValues={editData}
                >
                    <Form.Item
                        label="账号名"
                        name="account"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="用户组"
                        name="userGroup"
                    >
                        <Select
                            style={{ width: 120 }}
                            options={[
                                { value: '超级管理员', label: '超级管理员' },
                                { value: '普通管理员', label: '普通管理员' },
                            ]}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default AccountList;    